<?php

namespace App\Http\Controllers\Applet\User;

use App\Exceptions\UserException;
use App\Services\Applet\User\AddressService;
use Exception;
use Illuminate\Http\JsonResponse;

class AddressController extends BaseUserController
{
    protected AddressService $addressService;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->addressService = $this->loadService('Applet\User\AddressService');
    }

    /**
     * 我的地址列表
     * @return JsonResponse
     * @throws Exception
     */
    public function list(): JsonResponse
    {
        $list = $this->addressService->list();
        return outputJsonResult($list);
    }

    /**
     * 地址详情
     * @return JsonResponse
     * @throws UserException
     * @throws Exception
     */
    public function detail(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $data = $this->addressService->detail($this->params);
        return outputJsonResult($data);
    }

    /**
     * 添加地址
     * @return JsonResponse
     * @throws Exception
     */
    public function create(): JsonResponse
    {
        $rule = [
            'provinceId' => 'required|integer|min:1',
            'cityId' => 'required|integer|min:0',
            'regionId' => 'required|integer|min:0',
            'receiveName' => 'required|string|min:1',
            'receiveTel' => 'required|string|min:1',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->addressService->create($this->params);
        return outputJsonResult();
    }

    /**
     * 更新地址
     * @return JsonResponse
     * @throws Exception
     */
    public function update(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->addressService->update($this->params);
        return outputJsonResult();
    }

    /**
     * 删除地址
     * @return JsonResponse
     * @throws UserException
     */
    public function delete(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->addressService->delete($this->params);
        return outputJsonResult();
    }
}
